package com.yitongmao.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.bean.AddressBean;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bottompop.Area;
import com.yitongmao.bottompop.CityPicker;
import com.yitongmao.bottompop.CityUtil2;
import com.yitongmao.bottompop.FileUtil;
import com.yitongmao.bottompop.PopupWindowUtil;
import com.yitongmao.bottompop.SharedConfig;
import com.yitongmao.bottompop.SpKey;
import com.yitongmao.bottompop.ThreadUtils;
import com.yitongmao.bottompop.UIUtils;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

public class AmendActivity extends AppCompatActivity implements View.OnClickListener{
    private AutoLinearLayout mReceivingAddress;
    private EditText nick_name;
    private EditText user_phone;
    private EditText mMinuteAddress;
    private SharedPreferences sp;
    private AutoLinearLayout ziliao;
    private CityPicker fragmentCityPicker;
    private String dq;
    private TextView fragment_area;
    private ImageView mAddressmoren;
    private boolean flag = true;
    private Button mSaveAddress;
    private String citycode;
    private String countryCode;
    private String provicecode;
    private String status = "00";
    private String name;
    private String phone;
    private String address;
    private String id2;
    private Button btn_back;
    private LoginHuancunBean loginHuancunBean;
    private int loginId1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immerSion();
        setContentView(R.layout.activity_amend);
        initView();
        Intent intent=getIntent();
        String name = intent.getStringExtra("name");
        String phone = intent.getStringExtra("phone");
        String provinceName = intent.getStringExtra("provinceName");
        String cityName = intent.getStringExtra("cityName");
        String countryName = intent.getStringExtra("countryName");
        String address = intent.getStringExtra("address");
        id2 = intent.getStringExtra("id");
        String status = intent.getStringExtra("status");
        fragment_area.setText(provinceName+""+cityName+""+countryName);
        nick_name.setText(name);
        user_phone.setText(phone);
        mMinuteAddress.setText(address);
       /* if (status.equals("01")){
            mAddressmoren.setImageResource(R.drawable.dizhixuanzhong);
        }*/
        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {
                //初始化城市数据
                String area_str;
                if (sp == null)
                    sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
                String str = sp.getString(SpKey.AAASSEST2, "");
                if (!TextUtils.isEmpty(str))
                    area_str = str;
                else {
                    area_str = FileUtil.readAssets(UIUtils.getContext(), "a2.json");
                    sp.edit().putString(SpKey.AAASSEST2, area_str).commit();
                }
                Gson gson = new Gson();
                Area area = gson.fromJson(area_str, Area.class);
                CityUtil2 cityUtil2 = new CityUtil2(area);
                cityUtil2.initProvince();
                cityUtil2.initCity();
                cityUtil2.initCountry();
            }
        });

        setOnClick();
    }
    //沉浸式状态栏
    public void immerSion() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.BLACK);
        }
    }
    private void setOnClick() {
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AmendActivity.this.finish();
            }
        });
        //点击弹框
        mReceivingAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fishKey();
                View shanghu = PopupWindowUtil.toogleInButton(AmendActivity.this, SpKey.DQ, ziliao, R.layout.fragment_area);
                setPopupListener(shanghu);
            }
        });
        //点击设置默认地址
        mAddressmoren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag) {
                    status = "01";
                    mAddressmoren.setImageResource(R.drawable.dizhixuanzhong);
                    flag = false;
                } else {
                    mAddressmoren.setImageResource(R.drawable.dizhimeixuanzhong);
                    status = "00";
                    flag = true;
                }
            }
        });

    }
    public void fishKey() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(user_phone.getWindowToken(), 0);
        }
    }
    public void setPopupListener(View view) {
        fragmentCityPicker = (CityPicker) view.findViewById(R.id.fragment_cityPicker);
        Button fragment_area_confirm = (Button) view.findViewById(R.id.fragment_area_confirm);
        fragment_area_confirm.setOnClickListener(this);
    }
    private void initView() {
          Gson gson = new Gson();
        String loginId = ACache.get(AmendActivity.this).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            loginId1 = loginHuancunBean.userInfo.loginId;
        }
        btn_back = (Button) findViewById(R.id.btn_back);
        fragment_area = (TextView) findViewById(R.id.fragment_area);
        ziliao = (AutoLinearLayout) findViewById(R.id.ziliao);
        //保存
        //bt_header_rightAddress = (TextView) findViewById(R.id.bt_header_rightAddress);
        //姓名
        nick_name = (EditText) findViewById(R.id.nick_name);
        //手机号
        user_phone = (EditText) findViewById(R.id.user_phone);
        //详细地址
        mMinuteAddress = (EditText) findViewById(R.id.mMinuteAddress);
        mAddressmoren = (ImageView) findViewById(R.id.mAddressmoren);//设置默认地址
        mReceivingAddress = (AutoLinearLayout) findViewById(R.id.mReceivingAddress);
        //保存收获地址
        mSaveAddress = (Button) findViewById(R.id.mSaveAddress);
        //保存收货地址
        mSaveAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = nick_name.getText().toString().trim();
                phone = user_phone.getText().toString().trim();
                address = mMinuteAddress.getText().toString().trim();
                saveAddress(provicecode, citycode, countryCode, name, phone, address, id2,status);
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_area_confirm:
                String citys = fragmentCityPicker.getCity_string();
                provicecode = fragmentCityPicker.getProvicecode();
                citycode = fragmentCityPicker.getCitycode();
                countryCode = fragmentCityPicker.getCountryCode();
                String[] strings = citys.split("#");
                dq = "";
                for (String str : strings) {
                    dq = dq + str;
                }
                fragment_area.setText(dq);
                PopupWindowUtil.cancel(SpKey.DQ);
                break;
        }
    }
    public void saveAddress(String provinceId, String cityId, String countryId, final String name, final String phone, final String address, String id, final String status) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("provinceId", provinceId);
        params.put("cityId", cityId);
        params.put("countryId", countryId);
        params.put("name", name);
        params.put("phone", phone);
        params.put("address", address);
        params.put("id", id);
        params.put("status", status);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin",SignUtil.signLogin(nonce,timestamp));
        params.put("loginId",String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.amendtakeUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                Log.e("Gson", "" + string);
                Gson gson = new Gson();
                AddressBean addressBean = gson.fromJson(string, AddressBean.class);
                if (addressBean.result.state.equals("1")){
                    ToastUtils.showShort(AmendActivity.this,""+addressBean.result.message);
                    Intent intent=new Intent(AmendActivity.this,AddAddressActivity.class);
                    intent.putExtra("id","666");
                    startActivity(intent);
                    AmendActivity.this.finish();
                }
            }
            @Override
            public void onFail(Object result) {
                ToastUtils.showShort(AmendActivity.this, "失败");
            }
        });
    }
}
